﻿using System;

namespace winS.Unity.Process
{
    public class ProcessPlayState : IProcessPlayState
    {
        public event Action onPlayEnd;

        public bool isPlaying { get; private set; }

        bool ICustomCoroutineWait.customCoroutineWaitComplete => !isPlaying;

        internal Action continuation;

        private readonly Process process;

        internal ProcessPlayState(Process process)
        {
            //流程在创建的当前帧就跑完了, 我们仅调用结束事件
            if (!process.playing)
            {
                onPlayEnd?.Invoke();
                return;
            }
            isPlaying = true;
            this.process = process;
            process.onFinished += OnStop;
        }

        public void Stop()
        {
            process.Stop();
        }

        private void OnStop()
        {
            isPlaying = false;
            continuation?.Invoke();
            onPlayEnd?.Invoke();
            process.onFinished -= OnStop;
        }

        public ProcessAwaiter GetAwaiter()
        {
            return new ProcessAwaiter(this);
        }
    }
}
